package setup;

import utils.Var;
import utils.DBConnection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import java.util.Enumeration;
import java.util.List;
import java.util.ArrayList;
import java.sql.Connection;

import question.Classify;
import interceptor.InjectConnection;
import account.AccountUtils;

/**
 * Created by IntelliJ IDEA.
 * User: Shawn
 * Date: 2009-6-20
 * Time: 21:53:40
 */
public class SetupAction {

  private Connection con;

  @InjectConnection(autoCommit = DBConnection.AutoCommiteOff)
  public void setCon(Connection con) {
    this.con = con;
  }

  public String setup() throws Exception {
    HttpSession session = ServletActionContext.getRequest().getSession();
    if (!AccountUtils.hasRight(session, Var.RIGHT_SETUP)) throw new Exception("deny!");

    HttpServletRequest request = ServletActionContext.getRequest();
    Enumeration names = request.getParameterNames();

    List<SetupInfo> list = new ArrayList<SetupInfo>();
    while (names.hasMoreElements()) {
      String name = (String) names.nextElement();
      if (!name.startsWith("yd_")) continue;
      int ydID = Integer.parseInt(name.substring(name.indexOf("_") + 1));
      int value = request.getParameter(name).trim().length() == 0 ? 0 : Integer.parseInt(request.getParameter(name));
      list.add(new SetupInfo(ydID, value));
    }

    int dtID = Classify.getClassify(con, list.get(0).getYdID()).getParentID();
    int kmID = Classify.getClassify(con, dtID).getParentID();
    Setup.delSetup(con, kmID);
    Setup.addSetup(con, list);
    return Var.ACTION_SUCCESS;
  }
}
